<div class="layui-upload">
    <button type="button" class="layui-btn layui-btn-xs" id="multipleFileUploadBtn">选择文件</button>
    <input type="hidden" name="multiple_file" id="multiple_file">
    <div class="layui-upload-list">
        <table class="layui-table" lay-size="sm">
            <thead>
            <tr>
                <th width="80%">文件名</th>
                <th width="80%">操作</th>
            </tr>
            </thead>
            <tbody id="multipleFileBody">
            </tbody>
        </table>
    </div>
</div>
<script>
    layui.use(['jquery','form', 'layer','upload','element'], function () {
        var $ = layui.jquery;
        var form = layui.form;
        var layer = layui.layer;
        var upload = layui.upload;
        var element = layui.element;
            @if(isset($file) && $file)
        var files = "{{$file}}".split(",")
            @else
        var files = []
        @endif

        function updateFiles(){
            $("#multipleFileBody").html('');
            if (files.length>0){
                $("#multiple_file").val(files.join(','))
                files.forEach(function (v,index) {
                    var tr = $([
                        '<tr>',
                        '<td><a href="'+v+'" target="_blank">'+v+'</a></td>',
                        '<td><button type="button" class="layui-btn layui-btn-xs layui-btn-danger delBtn">删除</button></td>',
                        '</tr>'
                    ].join(''))
                    tr.find(".delBtn").on('click',function () {
                        tr.remove()
                        files.splice(index,1)
                        $("#multiple_file").val(files.join(','))
                    })
                    $("#multipleFileBody").append(tr)
                })
            }else {
                $("#multiple_file").val('')
            }
        }
        updateFiles();

        //多文件列表
        upload.render({
            elem: '#multipleFileUploadBtn'
            ,url: '{{route('api.upload')}}'
            ,accept: 'file'
            ,multiple: true
            ,number: 5
            ,auto: true
            ,before: function(obj){
                layer.load(); //上传loading
            }
            ,done: function(res, index, upload){ //成功的回调
                layer.closeAll('loading'); //关闭loading
                if(res.code === 0){ //上传成功
                    files.push(res.data.url)
                    updateFiles()
                    return;
                }
                layer.msg(res.msg,{icon:2})
            }
            ,error: function(index, upload){
                layer.closeAll('loading'); //关闭loading
                layer.msg('上传出错了');
            }
        });

    });
</script>
